package com.markerhub.service.impl;

import com.markerhub.common.lang.Result;
import com.markerhub.entity.TeachingCalling;
import com.markerhub.entity.TeachingCallingDetail;
import com.markerhub.entity.TeachingStudentInClass;
import com.markerhub.mapper.TeachingCallingDetailMapper;
import com.markerhub.mapper.TeachingCallingMapper;
import com.markerhub.mapper.TeachingStudentInClassMapper;
import com.markerhub.service.TeachingCallingService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class TeachingCallingServiceImpl extends ServiceImpl<TeachingCallingMapper, TeachingCalling> implements TeachingCallingService {
    @Autowired
    private TeachingCallingMapper callingMapper;

    @Autowired
    private TeachingCallingDetailMapper detailMapper;

    @Autowired
    private TeachingStudentInClassMapper studentInClassMapper;

    @Override
    @Transactional
    public Result startCalling(Integer classId, Integer teacherId) {
        // 先更新过期的点名状态
        updateExpiredCalls();

        // 检查是否有进行中的点名
        List<TeachingCalling> activeCalls = callingMapper.getActiveCallingsByClassId(classId);
        if (!activeCalls.isEmpty()) {
            return Result.fail("该班级已有进行中的点名");
        }

        // 创建点名记录
        TeachingCalling calling = new TeachingCalling();
        calling.setStartTime(LocalDateTime.now());
        calling.setEndTime(LocalDateTime.now().plusMinutes(5));
        calling.setEnded("0");
        calling.setCreator(teacherId);
        calling.setClassId(classId);
        callingMapper.insert(calling);

        // 获取班级所有学生
        List<TeachingStudentInClass> students = studentInClassMapper.selectByClassId(classId);

        // 为每个学生创建点名详情
        for (TeachingStudentInClass student : students) {
            TeachingCallingDetail detail = new TeachingCallingDetail();
            detail.setCallId(calling.getId());
            detail.setStuInClassId(student.getId());
            detail.setAnswerResult("0");
            detailMapper.insert(detail);
        }

        return Result.succ(calling);
    }

    @Override
    public Result getStudentPendingCalls(Integer studentId) {
        // 先更新过期的点名状态
        updateExpiredCalls();

        List<Map<String, Object>> pendingCallsByStudentId = callingMapper.getPendingCallsByStudentId(studentId);
        return Result.succ(pendingCallsByStudentId);
    }

    @Override
    @Transactional
    public Result studentAnswer(Integer callId, Integer studentId) {
        // 先获取学生在班级中的ID
        Integer stuInClassId = callingMapper.getStuInClassId(callId, studentId);
        if (stuInClassId == null) {
            return Result.fail("未找到您在该班级的记录");
        }
        TeachingCalling calling = callingMapper.selectById(callId);
        if (calling == null || "1".equals(calling.getEnded())) {
            return Result.fail("点名已结束");
        }
        if (LocalDateTime.now().isAfter(calling.getEndTime())) {
            return Result.fail("点名已过期");
        }
        TeachingCallingDetail detail = detailMapper.getStudentCallingDetail(callId, stuInClassId);
        if (detail == null) {
            return Result.fail("未找到点名记录");
        }
        detail.setAnswerTime(LocalDateTime.now());
        detail.setAnswerResult("1");
        detailMapper.updateById(detail);

        return Result.succ("签到成功");
    }

    @Override
    public Result getActiveCall(Integer classId) {
        // 先更新过期的点名状态
        updateExpiredCalls();

        TeachingCalling activeCalling = callingMapper.getActiveCall(classId);
        if (activeCalling == null) {
            return Result.succ(null);
        }

        // 获取点名详情
        List<TeachingCallingDetail> details = detailMapper.getCallingDetails(activeCalling.getId());

        Map<String, Object> data = new HashMap<>();
        data.put("calling", activeCalling);
        data.put("details", details);

        return Result.succ(data);
    }

    @Override
    public Result getCallingDetails(Integer callId) {
        List<TeachingCallingDetail> details = detailMapper.getCallingDetails(callId);
        return Result.succ(details);
    }

    // 更新过期的点名状态
    private void updateExpiredCalls() {
        callingMapper.updateExpiredCalls();
    }

    // 获取点名统计信息
    @Override
    public Result getCallingStats(Integer callId) {
        TeachingCalling calling = callingMapper.selectById(callId);
        if (calling == null) {
            return Result.fail("点名不存在");
        }

        List<TeachingCallingDetail> details = detailMapper.getCallingDetails(callId);

        Map<String, Object> stats = new HashMap<>();
        stats.put("total", details.size());
        stats.put("signed", details.stream().filter(d -> "1".equals(d.getAnswerResult())).count());
        stats.put("unsigned", details.stream().filter(d -> "0".equals(d.getAnswerResult())).count());

        return Result.succ(stats);
    }

    // 结束点名
    @Override
    @Transactional
    public Result endCalling(Integer callId) {
        TeachingCalling calling = callingMapper.selectById(callId);
        if (calling == null) {
            return Result.fail("点名不存在");
        }

        if ("1".equals(calling.getEnded())) {
            return Result.fail("点名已经结束");
        }

        calling.setEnded("1");
        calling.setEndTime(LocalDateTime.now());
        callingMapper.updateById(calling);

        return Result.succ("点名已结束");
    }
}
